
const id = window.location.href.split('=')[1]

// 渲染分类
function getCatagory() {
    request({
        type: 'get',
        url: '/admin/category/list',
        success: (res) => {
            if(res.code === 200){
                const renderResult = template('catagoryItem', res)
                $('.category').html(renderResult)
            }
        }
    })
}
getCatagory()
// 判断是否有id，有就把点击编辑那条对应的内容显示出来
if (id) {
    $('#edit').show() //把修改按钮显示出来
    request({
        type: 'get',
        url: '/admin/article/search',
        data: { id },
        success: (res) => {
            if (res.code === 200) {
                const { title, categoryId, cover, date, content } = res.data
                $('#inputTitle').val(title);
                $('#category').val(categoryId);
                $('.article_cover').attr('src', cover);
                $('#myDate').val(date);
                $('#articleContent').val(content);
              }
        }
    })
} else {
    $('#public').show() // 把发布按钮显示出来
}

// 初始化日期和富文本
function initPage() {
    jeDate('#myDate', {
    format: 'YYYY-MM-DD'
    });

    tinymce.init({
    selector: "#articleContent",
    language: 'zh_CN',
        })
}
initPage();

// 图片预览
function changeCoverImg() {
    const file = $('#inputCover')[0].files[0]
    const url = URL.createObjectURL(file)
    $('.article_cover').prop('src',url)
}

// 修改文章
function editArticle(state) {
    const formdata = new FormData($('#form')[0]) 
    const content = tinymce.activeEditor.getContent();
    formdata.append('state', state)
    formdata.append('content', content)
    formdata.append('id',id)
    formdata.delete('articleContent')
    request({
        type: 'post',
        url: '/admin/article/edit',
        data: formdata,
        success: (res) => {
            console.log(res)
            if(res.code === 200){
                alert(res.msg)
                window.location.href = "./article_list.html"
            }
        }
    })
    return false
}

// 发布文章
function publicArticle(state) {
    const formdata = new FormData($('#form')[0]) 
    const content = tinymce.activeEditor.getContent();
    formdata.append('state', state)
    formdata.append('content', content)
    formdata.delete('articleContent')
    request({
        type: 'post',
        url: '/admin/article/publish',
        data: formdata,
        success: (res) => {
            if(res.code === 200){
                alert(res.msg)
                window.location.href = "./article_list.html"
            }
        }
    })
    return false
}